package com.example.hasee.zhcd.Activities.ChuanWu;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.hasee.zhcd.Base.BaseActivity;
import com.example.hasee.zhcd.Bean.BrandItemInfo;
import com.example.hasee.zhcd.Bean.EventMsg;
import com.example.hasee.zhcd.Bean.ShipItemInfo;
import com.example.hasee.zhcd.R;
import com.example.hasee.zhcd.Util.GlobalParameter;
import com.example.hasee.zhcd.Util.NewDateTimePickDialogUtil;
import com.example.hasee.zhcd.Util.ProgressDialogUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import static com.example.hasee.zhcd.R.id.start_date;

public class OBInputActivity extends BaseActivity {
    private HashMap<String, String> loginmap = (HashMap<String, String>) GlobalParameter.get("loginmap");
    private TextView title;
    private ImageView back;
    private ImageView home;
    private EditText ship;
    private EditText date;
    private EditText work;
    private EditText beizhu;
    private Button btn_save;
    private String strSYN = "";
    private String strShipCode = "";
    private String strFID = "";
    private String strUser = "";
    private String strDLSJ = "";
    private String strGZNR = "";
    private String strAccount = "";
    private String strBZ = "";
    private String shipnameString = "";
    private String worknameString = "";
    public static ArrayList<BrandItemInfo> brandInfoList = new ArrayList<BrandItemInfo>();
    public static ArrayList<ShipItemInfo> shipInfoList = new ArrayList<ShipItemInfo>();
    private Boolean isadd;

    @Override
    public int contentViewId() {
        return R.layout.activity_ob_input;
    }

    @Override
    public void set() {
        title.setText("外勤管理");
        back.setOnClickListener(this);
        home.setVisibility(View.INVISIBLE);
        ship.setOnClickListener(this);
        date.setOnClickListener(this);
        work.setOnClickListener(this);
        btn_save.setOnClickListener(this);
        if ("0".equals(strSYN)) {
            getShipBase();
        } else {
            OBDetail();
        }
    }

    @Override
    public void init() {
        strUser = loginmap.get("user");
        strAccount = loginmap.get("account");
        isadd = getIntent().getExtras().getBoolean("add");
        strSYN = getIntent().getExtras().getString("fsyn");
        strFID = getIntent().getExtras().getString("fid");
        strShipCode = getIntent().getExtras().getString("fshipcode");
        title = (TextView) findViewById(R.id.centertitle);
        back = (ImageView) findViewById(R.id.back);
        home = (ImageView) findViewById(R.id.home);
        ship = (EditText) findViewById(R.id.ship);
        date = (EditText) findViewById(R.id.date);
        work = (EditText) findViewById(R.id.work);
        beizhu = (EditText) findViewById(R.id.beizhu);
        btn_save = (Button) findViewById(R.id.btn_save);

    }

    @Override
    public void getEventData(EventMsg msg) {
        switch (msg.getAction()) {
            case "Fail":
                ProgressDialogUtils.closeProgressDialog();
                Toast.makeText(OBInputActivity.this, "操作失败，请检查网络！", Toast.LENGTH_LONG).show();
                break;
            case "ZHCW_wqgl_ship":
                ProgressDialogUtils.closeProgressDialog();
                try {
                    JSONObject json = new JSONObject(msg.getMsg());
                    String rspcode = json.getString("rspcode");
                    String rspmessage = json.getString("rspmessage");
                    shipInfoList.clear();
                    if ("0".equals(rspcode)) {
                        JSONArray data = json.getJSONArray("data");
                        for (int i = 0; i < data.length(); i++) {
                            ShipItemInfo info = new ShipItemInfo();
                            info.setRolename(data.getJSONObject(i).getString("fname"));
                            info.setRolecode(data.getJSONObject(i).getString("fcode"));
                            info.setSYN(data.getJSONObject(i).getString("fsyn"));
                            info.setSelected(false);
                            shipInfoList.add(info);
                        }

                    } else {

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (!isadd) {
                    getWorkBase();
                }
                break;
            case "ZHCW_wqgl_gznr":
                ProgressDialogUtils.closeProgressDialog();
                try {
                    JSONObject json = new JSONObject(msg.getMsg());
                    String rspcode = json.getString("rspcode");
                    String rspmessage = json.getString("rspmessage");
                    brandInfoList.clear();
                    if ("0".equals(rspcode)) {
                        JSONArray data = json.getJSONArray("data");
                        for (int i = 0; i < data.length(); i++) {
                            BrandItemInfo info = new BrandItemInfo();
                            info.setShipname(data.getJSONObject(i).getString("fname"));
                            info.setShipcode(data.getJSONObject(i).getString("fcode"));
                            info.setSelected(false);
                            brandInfoList.add(info);
                        }
                        if (!"".equals(strGZNR)) {
                            String[] allship = strGZNR.split("\\,");
                            for (int i = 0; i < allship.length; i++) {
                                for (int j = 0; j < brandInfoList.size(); j++) {
                                    if (allship[i].equals(brandInfoList.get(j).getShipcode())) {
                                        brandInfoList.get(j).setSelected(true);
                                    }
                                }
                            }
                        }
                    } else {

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case "ZHCW_wqgl_detail":
                ProgressDialogUtils.closeProgressDialog();
                //E/ZHCW_wqgl_detail: {"data": [{"fsyn":"QHD201802254", "fship":"广茂", "fdlsj":"2018-06-05 18:20",
                // "fgznr":"9094", "fgznrname":"其他事项", "fbz":"", "ftznr":"9094,"}],"rspcode": 0,"rspmessage":""}
                try {
                    JSONObject json = new JSONObject(msg.getMsg());
                    String rspcode = json.getString("rspcode");
                    String rspmessage = json.getString("rspmessage");
                    if ("0".equals(rspcode)) {
                        JSONArray data = json.getJSONArray("data");
                        JSONObject body = data.getJSONObject(0);
                        strSYN = body.getString("fsyn");
                        strDLSJ = body.getString("fdlsj");

                        ship.setText(body.getString("fship"));
                        date.setText(strDLSJ);
                        work.setText(body.getString("fgznrname"));
                        strGZNR = body.getString("fgznr");
                        strBZ = body.getString("fbz");
                    } else {

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                getShipBase();
                break;
            case "ZHCW_WQAdd":
                ProgressDialogUtils.closeProgressDialog();
                //ZHCW_WQAdd: {"data":"","rspcode": 1,"rspmessage":"添加成功！"}
                try {
                    JSONObject json = new JSONObject(msg.getMsg());
                    String rspcode = json.getString("rspcode");
                    String rspmessage = json.getString("rspmessage");
                    if ("1".equals(rspcode)) {
                        FinishDialog(rspmessage);
                    } else {
                        Toast.makeText(OBInputActivity.this, rspmessage, Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case "ZHCW_WQMod":
                ProgressDialogUtils.closeProgressDialog();
                try {
                    JSONObject json = new JSONObject(msg.getMsg());
                    String rspcode = json.getString("rspcode");
                    String rspmessage = json.getString("rspmessage");
                    if ("1".equals(rspcode)) {
                        FinishDialog(rspmessage);
                    } else {
                        Toast.makeText(OBInputActivity.this, rspmessage, Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
        }
    }

    private void getShipBase() {
//        ProgressDialogUtils.createProgressDialog(OBInputActivity.this,"正在获取数据...");
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("strSYN", strSYN);
        httpUtils.get("ZHCW_wqgl_ship", map, "ZHCW_wqgl_ship");
    }

    private void getWorkBase() {
//        ProgressDialogUtils.createProgressDialog(OBInputActivity.this,"正在获取数据...");
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("strSYN", strSYN);
        map.put("strShipCode", strShipCode);
        map.put("strFID", strFID);
        httpUtils.get("ZHCW_wqgl_gznr", map, "ZHCW_wqgl_gznr");
    }

    private void OBDetail() {
        ProgressDialogUtils.createProgressDialog(OBInputActivity.this, "正在获取数据...");
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("strFID", strFID);
        httpUtils.get("ZHCW_wqgl_detail", map, "ZHCW_wqgl_detail");
    }

    private void addOB() {
        ProgressDialogUtils.createProgressDialog(OBInputActivity.this, "正在提交数据...");
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("strSYN", strSYN);
        map.put("strUser", strUser);
        map.put("strDLSJ", strDLSJ);
        map.put("strGZNR", strGZNR);
        map.put("strAccount", strAccount);
        map.put("strBZ", strBZ);
        httpUtils.get("ZHCW_WQAdd", map, "ZHCW_WQAdd");
    }

    private void modOB() {
        ProgressDialogUtils.createProgressDialog(OBInputActivity.this, "正在提交数据...");
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("strSYN", strSYN);
        map.put("strUser", strUser);
        map.put("strDLSJ", strDLSJ);
        map.put("strGZNR", strGZNR);
        map.put("strAccount", strAccount);
        map.put("strBZ", strBZ);
        map.put("strFID", strFID);
        httpUtils.get("ZHCW_WQMod", map, "ZHCW_WQMod");
    }

    private View inputCheck() {
        if (strSYN.length() == 0) {
            Toast.makeText(OBInputActivity.this, "请选择船舶！", Toast.LENGTH_LONG).show();
            return ship;
        } else if (strDLSJ.length() == 0) {
            Toast.makeText(OBInputActivity.this, "请选择登轮时间！", Toast.LENGTH_LONG).show();
            return date;
        } else if (strGZNR.length() == 0) {
            Toast.makeText(OBInputActivity.this, "当前船舶暂无工作内容或您未选择工作内容，请检查后进行保存操作！", Toast.LENGTH_LONG).show();
            return work;
        }
        return null;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.work:
                if ("0".equals(strSYN) || "".equals(strSYN)) {
                    Toast.makeText(OBInputActivity.this, "没选船，选什么工作内容！", Toast.LENGTH_LONG).show();
                } else {
                    workDialog();
                }
                break;
            case R.id.ship:
                singleDialog();
                break;
            case R.id.date:
                String t1 = "";
                if (date.getText().toString().equals("")) {
                    t1 = getTime();
                } else {
                    t1 = date.getText().toString();
                }
                NewDateTimePickDialogUtil dialog1 = new NewDateTimePickDialogUtil(this,
                        t1);
                dialog1.dateTimePicKDialog(date);
                break;
            case R.id.btn_save:
                strDLSJ = date.getText().toString().trim();
                View errorview = inputCheck();
                if (errorview != null) {
                    errorview.setFocusable(true);
                    errorview.requestFocus();
                    errorview.setFocusableInTouchMode(true);
                    return;
                } else {
                    if (isadd) {
                        addOB();
                    } else {
                        modOB();
                    }
                }
                break;
        }
    }

    public String getTime() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");// 设置日期格式
        return df.format(new Date());// new Date()为获取当前系统时间
    }

    /**
     * 弹框工具
     */
    public void singleDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater = getLayoutInflater();
        final View layout = inflater.inflate(R.layout.list_dialog, null);
        builder.setView(layout);
        ListView shiplist = (ListView) layout.findViewById(R.id.dialog_list);
        final SingleAdapter shipadapter = new SingleAdapter();
        shiplist.setAdapter(shipadapter);
        final AlertDialog dialog = builder.create();
        Button ship_sure = (Button) layout.findViewById(R.id.ship_sure);
        ship_sure.setVisibility(View.GONE);
        shiplist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                shipnameString = shipInfoList.get(position).getRolename();
                strShipCode = shipInfoList.get(position).getRolecode();
                strSYN = shipInfoList.get(position).getSYN();
                ship.setText(shipnameString);
                work.setText("");
                strGZNR = "";
                getWorkBase();
                dialog.dismiss();
            }
        });

        dialog.show();
    }

    public void workDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater = getLayoutInflater();
        final View layout = inflater.inflate(R.layout.list_dialog, null);
        builder.setView(layout);
        ListView shiplist = (ListView) layout.findViewById(R.id.dialog_list);
        final WorkAdapter shipadapter = new WorkAdapter();
        shiplist.setAdapter(shipadapter);
        final AlertDialog dialog = builder.create();
        Button ship_sure = (Button) layout.findViewById(R.id.ship_sure);
        ship_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                worknameString = "";
                strGZNR = "";
                for (int i = 0; i < brandInfoList.size(); i++) {
                    if (brandInfoList.get(i).isSelected() == true) {
                        if ("".equals(strGZNR)) {
                            worknameString = brandInfoList.get(i).getShipname();
                            strGZNR = brandInfoList.get(i).getShipcode();
                        } else {
                            worknameString = worknameString + "," + brandInfoList.get(i).getShipname();
                            strGZNR = strGZNR + "," + brandInfoList.get(i).getShipcode();
                        }

                    }
                }
                work.setText(worknameString);
                dialog.dismiss();
            }

        });

        dialog.show();
    }

    /*
    * 内部类适配器
    * */
    class WorkAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return brandInfoList.size();
        }

        @Override
        public Object getItem(int position) {
            return null != brandInfoList ? brandInfoList.get(position) : null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Holder holder = null;
            BrandItemInfo brandItemInfo = (BrandItemInfo) getItem(position);
            if (null == holder) {
                LayoutInflater inflater = (LayoutInflater) OBInputActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.ship_list_item, null);
                holder = new Holder();
                holder.workbox = (CheckBox) convertView.findViewById(R.id.ship_box);
                final Holder fholder = holder;
                holder.workbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        BrandItemInfo info = (BrandItemInfo) fholder.workbox.getTag();
                        info.setSelected(buttonView.isChecked());
                    }
                });
                convertView.setTag(holder);
                holder.workbox.setTag(brandItemInfo);
            } else {
                holder = (Holder) convertView.getTag();
                holder.workbox.setTag(brandItemInfo);
            }
            holder.workbox.setText(brandItemInfo.getShipname());
            holder.workbox.setChecked(brandItemInfo.isSelected());
            return convertView;
        }

        private class Holder {
            private CheckBox workbox;
        }
    }

    class SingleAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return shipInfoList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Holder holder = null;
            ShipItemInfo shipItemInfo = (ShipItemInfo) shipInfoList.get(position);
            if (null == holder) {
                LayoutInflater inflater = (LayoutInflater) OBInputActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.role_list_item, null);
                holder = new Holder();
                holder.ship_text = (TextView) convertView.findViewById(R.id.ship_text);
                convertView.setTag(holder);
            } else {
                holder = (Holder) convertView.getTag();
            }
            holder.ship_text.setText(shipItemInfo.getRolename());
            return convertView;
        }

        private class Holder {
            private TextView ship_text;
        }
    }

    private void FinishDialog(String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(OBInputActivity.this);
        builder.setMessage(message);
        builder.setTitle("提示");
        builder.setNegativeButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub
                arg0.dismiss();
                OBInputActivity.this.finish();
            }
        });
        builder.create().setCanceledOnTouchOutside(false);
        builder.setCancelable(false);
        builder.show();
    }
}
